package com.adminserver.websocket;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
@ServerEndpoint("/realTimeService/{satoken}")
public class WebSocket {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private String satoken = "";

    /**
     * websocket连接成功调用方法
     *
     * @param session
     * @param satoken
     */
    @SneakyThrows
    @OnOpen
    public void onOpen(Session session, @PathParam("satoken") String satoken) {
        this.session = session;
        this.satoken = satoken;
        boolean add = webSocketSet.add(this);
        if (add) {
            addOnlineCount();
            session.getBasicRemote().sendText(satoken + "连接后勤管理系统成功");
        }
    }

    @SneakyThrows
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自{}的消息：{}", satoken, message);
        session.getBasicRemote().sendText(satoken + "你好！我已经收到你的消息");
    }

    @OnClose
    public void onClose() {
        boolean remove = webSocketSet.remove(this);
        if (remove) subOnlineCount();
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    //================================构建方法====================================

    public static int getOnlineCount() {
        return onlineCount.get();
    }

    public static void addOnlineCount() {
        onlineCount.getAndIncrement();
        log.info("有一新客户端连接成功，当前在线客户端：{}", getOnlineCount());
    }

    public static void subOnlineCount() {
        onlineCount.getAndDecrement();
        log.info("有一个客户端连接断开，当前在线客户端：{}", getOnlineCount());
    }

    /**
     * 单发消息推送
     *
     * @param message  消息
     * @param socketID socketID
     */
    @SneakyThrows
    public static void sendMessage(String message, String socketID) {
        for (WebSocket item : webSocketSet) {
            if (socketID.contains(item.satoken)) {
                item.session.getBasicRemote().sendText(message);
            }
        }
    }
}
